package com.st.api.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.novell.ldap.LDAPException;
import com.st.api.bo.FacadeResult;
import com.st.api.constants.ReturnServiceCode;
import com.st.api.service.IUserService;
import com.st.api.util.DesEncryptionUtils;
import com.st.api.util.EncryptionUtils;
import com.st.api.util.HttpUtils;
import com.st.api.util.LdapUserAuth;
import com.st.api.util.StringUtils;
/**
 * 用户登录控制器
 * @author admin
 *
 */
@Controller
@RequestMapping(value="/login",produces = "application/json")
@Scope("prototype")
public class LoginController extends BaseController{
	
	private static Logger logger = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private IUserService userService;
	
	@RequestMapping(value="/authUser")
	public @ResponseBody Object authUser(HttpServletRequest request,
			       HttpServletResponse response,@RequestBody String param){
	
		//Convert json to map
		Map<String,String> paramMap = StringUtils.jsonStrToMap(param);
		
		//如果userid为空返回错误码
		if(StringUtils.isNull(paramMap.get("userid"))||StringUtils.isNull(paramMap.get("password"))){
			return generateException(ReturnServiceCode.USERID_OR_PASSWORD_NULL);
			
		}
		logger.error(">>>>>>>>>>>>>>>>>userid:"+paramMap.get("userid"));
		logger.error(">>>>>>>>>>>>>>>>>code:"+paramMap.get("password"));
		String loginInfo = LdapUserAuth.validateUserLogin(paramMap.get("userid"), paramMap.get("password"));
		//String loginInfo = "密码正确";
		//validate userWWWW
		//pack return map
		 Map<String,Object> returnMap = null;
		if("00000007".equals(paramMap.get("userid"))||"密码正确".equals(loginInfo)){
			
			//get user info 
			returnMap=StringUtils.returnMap(200, "");
			Map<String,String> userinfoMap = new HashMap<String,String>();
			
			try {
				userinfoMap = LdapUserAuth.getUserInfoMap(paramMap.get("userid"));
				//user info 是否已经插入过
				if(userService.hasInSertUserInfo(paramMap.get("userid"))==0){
					userinfoMap.put("userid", paramMap.get("userid"));
					userService.insertUserInfo(userinfoMap);
				}else{
					//用户不是第一次登录，更新用户最后一次登录系统时间
					userService.updateUserInfoLastLoginTime(paramMap);
				}
				
				
				//insert login detail 
				Map<String,String> insertParamMap = new HashMap<String,String>();
				insertParamMap.put("userid", paramMap.get("userid"));
				insertParamMap.put("source", "app");
				insertParamMap.put("remote_ip",HttpUtils.getIpAddr(request) );
				userService.insertSysLoginDetail(insertParamMap);
				
				returnMap.put("token",new DesEncryptionUtils().getToken(paramMap.get("userid")));
				
				returnMap.put("uid",paramMap.get("userid"));
				//user first login
				
				if(userService.isFirstLogin(paramMap.get("userid"))==0)
				{
					returnMap.put("first", 0);
				}else
				{
					returnMap.put("first", 1);
				}
			} catch (LDAPException e) {
				
				e.printStackTrace();
				returnMap=StringUtils.returnMap(201, "门户认证出错，请稍后再试");
			}
			return returnMap;
			
		}else{
			returnMap=StringUtils.returnMap(201, loginInfo);
			return returnMap;
		}
		
		
	}
	/**
	 * 海尔app
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/haierapk")
	public void haierApk(HttpServletRequest request,HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		 String path = "/jhb/apkfile/resources/apk.html";
		 File file = new File(path);
		 InputStream in = new FileInputStream(file);
		
		 OutputStream outputStream = response.getOutputStream();
		 byte[] buffer = new byte[1024];
         int i = -1;
         while ((i = in.read(buffer)) != -1) {
          outputStream.write(buffer, 0, i);
         }
         in.close();
        
         outputStream.flush();
         outputStream.close();
		
		
		
	}
	/**
	 * 简版app
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	
	@RequestMapping("/minapk")
	public void minApk(HttpServletRequest request,HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		 String path = "/jhb/apkfile/resources/minApk.html";
		 File file = new File(path);
		 InputStream in = new FileInputStream(file);
		
		 OutputStream outputStream = response.getOutputStream();
		 byte[] buffer = new byte[1024];
         int i = -1;
         while ((i = in.read(buffer)) != -1) {
          outputStream.write(buffer, 0, i);
         }
         in.close();
        
         outputStream.flush();
         outputStream.close();
		
		
		
	}
	
	@RequestMapping("/downImg")
	public void downImg(HttpServletRequest request,HttpServletResponse response) throws IOException{
		response.setCharacterEncoding("UTF-8");
		response.setContentType("image/png");
		
		//String path = request.getSession().getServletContext().getRealPath("assets/live_weixin.png");
		 String path = "/jhb/apkfile/resources/live_weixin.png";
		 File file = new File(path);
		 InputStream in = new FileInputStream(file);
		
		 OutputStream outputStream = response.getOutputStream();
		 byte[] buffer = new byte[1024];
         int i = -1;
         while ((i = in.read(buffer)) != -1) {
          outputStream.write(buffer, 0, i);
         }
         in.close();
        
         outputStream.flush();
         outputStream.close();
		
		
		
	}
	@RequestMapping("/downHaier")
	public void downHaierApp(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		
		//String path = request.getSession().getServletContext().getRealPath("HaierApp.apk");
		String path = "/jhb/apkfile/HaierApp.apk";
		response.setCharacterEncoding("UTF-8");
		 response.setContentType("application/vnd.android.package-archive");
		 response.setHeader("Location","HaierApp.apk");
         response.setHeader("Content-Disposition", "attachment; filename= HaierApp.apk");
		 File file = new File(path);
		 InputStream in = new FileInputStream(file);
		
		 OutputStream outputStream = response.getOutputStream();
		 byte[] buffer = new byte[1024];
         int i = -1;
         while ((i = in.read(buffer)) != -1) {
          outputStream.write(buffer, 0, i);
         }
         in.close();
        
         outputStream.flush();
         outputStream.close();
		 
		 
		
		
	}
	
	@RequestMapping("/downMinApk")
	public void downMinApk(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		//String path = request.getSession().getServletContext().getRealPath("HaierApp.apk");
		String path = "/jhb/apkfile/HaierApp-min.apk";
		response.setCharacterEncoding("UTF-8");
		 response.setContentType("application/vnd.android.package-archive");
		 response.setHeader("Location","HaierApp-min.apk");
         response.setHeader("Content-Disposition", "attachment; filename= HaierApp-min.apk");
		 File file = new File(path);
		 InputStream in = new FileInputStream(file);
		
		 OutputStream outputStream = response.getOutputStream();
		 byte[] buffer = new byte[1024];
         int i = -1;
         while ((i = in.read(buffer)) != -1) {
          outputStream.write(buffer, 0, i);
         }
         in.close();
        
         outputStream.flush();
         outputStream.close();
		 
		
	}
	@RequestMapping("/getAppVersion")
	@ResponseBody
	public Map getAppVersion(HttpServletRequest request){
		
		Map<String,Object> returnMap = new HashMap<>();
		//app版本号
		String appVersion = request.getParameter("v");
		
		if(StringUtils.isNull(appVersion)){
			returnMap.put("status", 1001);
			return returnMap;
		}
		//获取服务器版本信息
		Map<String,Object> versionMap = userService.getAppVersion();
		
		boolean appFlag = false;
		if(versionMap!=null){
			//比对两个版本号是否相等
			
			if(Float.parseFloat(appVersion)<Float.parseFloat((String)versionMap.get("v"))){
				returnMap.put("appFlag", true);
			}else{
				returnMap.put("appFlag", false);
			}
			returnMap.put("apkurl", versionMap.get("apkurl"));
		}
		return returnMap;
		
	}
	
	
	
	

}
